﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TextTemplating.VSHost;
using System.Xml;
using System.IO;
using Microsoft.VisualStudio.TextTemplating;
using System.Runtime.InteropServices;

namespace RBTools.CodeGenerator.CodeDomGenerator
{
    [GuidAttribute("359C6236-D495-4789-8327-15BDD20D200C")]
    public class ExtendEntityDataModelGenerator : BaseCodeGeneratorWithSite
    {

        #region Generate FileContent

        protected string GenerateCode()
        {
            StringBuilder codeBuilder = new StringBuilder();

            codeBuilder.AppendFormat("<?xml version=\"1.0\" encoding=\"utf-8\" ?>{0}",Environment.NewLine);
            codeBuilder.AppendFormat("<extedmx>{0}</extedmx>{0}",Environment.NewLine);

            return codeBuilder.ToString();
        }

        #endregion

        #region Implement BaseCodeGeneratorWithSite

        protected override byte[] GenerateCode(string inputFileName, string inputFileContent)
        {
            string templateFileName = Path.ChangeExtension(inputFileName, ".extedmx");

            // Check to see if the T4 Script file is open in Visual Studio editor
            EnvDTE.Document templateDocument = this.Dte.Documents.Cast<EnvDTE.Document>().SingleOrDefault(d => d.FullName == templateFileName);
            if (templateDocument != null && !templateDocument.Saved)
            {
                // Save the script file if it was modified
                templateDocument.Save(string.Empty);
            }
            
            string templateFileContent;
            Encoding templateEncoding;

            // If the T4 script file already exists
            if (File.Exists(templateFileName))
            {
                // Read it from disk
                templateEncoding = EncodingHelper.GetEncoding(templateFileName);
                templateFileContent = File.ReadAllText(templateFileName, templateEncoding);
            }
            else
            {
                // Otherwise, create a new, empty one
                templateEncoding = Encoding.UTF8;

                // Select the programming language for the script based on the language of the project it belongs to
                const string VisualBasicProject = "{F184B08F-C81C-45F6-A57F-5ABD9991F28F}";
                EnvDTE. Project currentProject = this.Dte.Solution.FindProjectItem(inputFileName).ContainingProject;
                string language = string.Compare(currentProject.Kind, VisualBasicProject, StringComparison.OrdinalIgnoreCase) == 0
                    ? "VB"
                    : "C#";

                templateFileContent = GenerateCode();
            }

            return templateEncoding.GetBytes(templateFileContent);
        }

        public override string GetDefaultExtension()
        {
            return ".extedmx";
        }

        #endregion

    }
}
